package com.demo.exception;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.demo.dto.BaseResult;

/**
 * 错误信息统一处理 对未处理的错误信息做一个统一处理
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@ResponseBody
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) {

		logger.error("访问" + request.getRequestURI() + " 发生错误, 错误信息:" + ex.getMessage());
		try {
			PrintWriter writer = response.getWriter();
			BaseResult<Object> result = new BaseResult<Object>(false,
					ex.getMessage(), 500);
			writer.write(JSON.toJSONString(result));
			writer.flush();
		} catch (Exception e) {
			logger.error("Exception:", e);
		}

		return null;
	}
}
